local M=_G.ServerOHOH.class.new(script,_G.ServerOHOH.files.BaseComponent());
local FriendClass=_G.CommonOHOH.load.FriendCharacter()
local PlayerCharacterHelper = _G.CommonOHOH.load.PlayerCharacterHelper();
-- 控制生成跟随Bro 实体

function M.new(self,...)
	return M(self,...);
end;

function M.ctor(self, parent)
	M.super.ctor(self, parent);	
    self.player=self.parent.player
    local folder= Instance.new("Folder",workspace)
	folder.Name="Friend".. self.player:GetUserId()
	-- local folder= Instance.new("Folder",self.parent.main_inst)
    -- folder.Name="Friend"

    self.Floder=folder
	-- self.AttachmentList={}
	self.Obj2Att={}
	self.AttUsed={}

    self.ObjList={}
    
    ----生成装备点位
    for k,v in pairs(workspace.FriendPos:GetDescendants()) do
		local att= Instance.new("Attachment",self.parent:GetRootPart_Loop())
		att.CFrame=v.Value
		att.Name="FriendFollowAtt_"..k
        att:SetAttribute("isUsing",false)
		-- self.AttachmentList[k]=att
	end

    self.DataStore=self.player:GetComponent(_G.ServerOHOH.load.Server_PlayerDataComponent())

    self:Update(self.DataStore:GetData("bro").equip.__real)

    self.player.UserDataEvent:Connect(function(key)
        if key=="bro" then
            self:Update(self.DataStore:GetData("bro").equip.__real)
        end
    end)
    
end;

function M.dtor(self)

    for guid,v in pairs(self.ObjList) do
        v:dtor()
    end
    self.ObjList={}

    -- self.AttachmentList={}
	-- self.Obj2Att={}
	-- self.AttUsed={}

    self.Floder:Destroy()
   
	M.super.dtor(self);
end;

function M.Update(self,equip)
    local had={}
    for _,guid in pairs(equip) do 
        had[guid]=true
    end

    for k,v in pairs(self.ObjList) do --删除已经卸载的
        if not had[k] then
            v:dtor()
            self.ObjList[k]=nil
        end
    end

    for k,v in pairs(had) do
        if not self.ObjList[k] then --不存在，创建新的

            self.ObjList[k]=true
            self:CreateObj(k,self.DataStore:GetData("bro").had.__real[k])
            -- task.wait()
        end
    end

end


-- function M.findAtt(self,guid)

--     if self.Obj2Att[guid] then
--         return  self.Obj2Att[guid]
--     end

--     for k,v in ipairs(self.AttachmentList) do
-- 		if not self.AttUsed[v] then
--             self.Obj2Att[guid]=v
--             self.AttUsed[v]=true
--             return  v
-- 		end
-- 	end
-- end

-- function M.clearAtt(self,guid,att)
--     self.Obj2Att[guid]=nil
--     self.AttUsed[att]=nil
-- end


function M.CreateObj(self,guid,data)
    PlayerCharacterHelper.GetPlayerCharacter(data.userId,function(character)
        -- local att=self:findAtt(guid)
        if not character then
            self.ObjList[guid]=nil
        end
        local friend=FriendClass.new(character,self.player,guid,data,self.Floder)
        friend.DtorEvent:Connect(function()
            self.ObjList[guid]=nil
            -- self:clearAtt(guid,att)
        end)
        self.ObjList[guid]=friend
    end)
end


return M